//
//  WBMainViewController.swift
//  CFZWeiBo
//
//  Created by Cedric Zheng on 23/11/2016.
//  Copyright © 2016 Cedric Zheng. All rights reserved.
//

import UIKit

class WBMainViewController: UITabBarController {
    
    fileprivate lazy var composeButton: UIButton = UIButton(title: nil, imageName: "tabbar_compose_icon_add", bgImageName: "tabbar_compose_button")
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.softColor(withHue: .blueHue)
        
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        tabBar.bringSubview(toFront: composeButton)
    }
}

// MARK: - Setup method
extension WBMainViewController {
    
    fileprivate func setupUI() {
        
        setupChildViewControllers()
        
        addcomposeButton()
        
        if WBUserAccount.shared.hasLogin {
            setupNewFeatureOrWelcome()
        }
    }
    
    fileprivate func setupChildViewControllers() {
        
        guard
            let url     = Bundle.main.url(forResource: "main.json", withExtension: nil),
            let data    = try? Data(contentsOf: url),
            let controllersDictArray = try? JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]]
            else {
                return
        }
        
        for dict in controllersDictArray {
            guard
                let className       = dict["clsName"] as? String,
                let controllerClass = NSClassFromString(Bundle.main.nameSpace + "." + className) as? WBRootViewController.Type
                else {
                    continue
            }
            
            let title       = dict["title"] as? String
            let imageName   = dict["imageName"] as? String
            
            let controller  = controllerClass.init()
            
            addChildViewController(controller, title: title, imageName: imageName)
            
        }
    }
    
    /// Reload super's method, adding more parameters
    ///
    /// - Parameters:
    ///   - childController: the controller that need to be added
    ///   - title: title of the child controller
    ///   - imageName: the image that will show at tabbar
    fileprivate func addChildViewController(_ childController: UIViewController, title: String?, imageName: String?) {
        childController.title = title
        
        childController.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize:11), NSForegroundColorAttributeName: UIColor.darkGray], for: .normal)
        childController.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize:11), NSForegroundColorAttributeName: globalColor], for: .selected)
        
        if let imageName = imageName {
            childController.tabBarItem.image = UIImage(named: "tabbar_\(imageName)")?.withRenderingMode(.alwaysOriginal)
            childController.tabBarItem.selectedImage = UIImage(named: "tabbar_\(imageName)_selected")?.withRenderingMode(.alwaysOriginal)
        }
        
        let navigationController = UINavigationController(rootViewController: childController)
        
        addChildViewController(navigationController)
    }
    
    /// Add a compose button to tabbar, which wiss cover some part of the tabbar, should reserve some place for it.
    fileprivate func addcomposeButton() {
        tabBar.addSubview(composeButton)
        let frame = tabBar.bounds
        composeButton.frame     = frame.insetBy(dx: screenWidth/5 * 2 - 1.0, dy: 0.0)
        composeButton.center    = CGPoint(x: tabBar.center.x, y: tabBar.bounds.size.height/2)
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    fileprivate func setupNewFeatureOrWelcome() {
        if isAppVersionNew {
            let newFeatureView = WBNewFeatureView()
            view.addSubview(newFeatureView)
        } else {
            let welcomeView = WBWelcomeView()
            view.addSubview(welcomeView)
        }
    }

}

// MARK: - Private methods
extension WBMainViewController {
    @objc fileprivate func composeStatus() {
        print("You just tapped compose button.")
    }
}


